import CodoBase from "../../../lib/CodoBase";
import CodoError from "../../../lib/CodoError";

export default class CodoWechatMPCodeAndLink extends CodoBase {
	/**
	 * 获取不限制的根据scene参数生成的小程序二维码
	 *
	 * @param {string} scene
	 * @param {GetUnlimitedQRCodeParams} params
	 * @param {string} [access_token]
	 * @memberof CodoWechatMPCodeAndLink
	 */
	async getUnlimitedQRCode(scene: string, params: GetUnlimitedQRCodeParams, access_token?: string) {
		access_token = access_token || this.app.codo.wechat.mp.accessToken.getCurrentContextCacheAccessToken();
		const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`;
		const res = await this.app.curl(url, {
			method: "POST",
			data: {
				scene,
				...params,
			},
			rejectUnauthorized: false,
			dataType: "buffer",
		});

        if (res.data.errcode) {
			throw new CodoError(`mp生成scene二维码出错，errcode %s，errmsg %s`, res.data.errcode, res.data.errmsg);
		}
		return res.data as Buffer;

	}

	/**
	 * 小程序生成永久二维码，有数量限制，详见文档
	 *
	 * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/createQRCode.html
	 *
	 * @param {string} path 小程序页面路径
	 * @param {number} [width=430] 二维码宽度
	 * @param {string} [access_token]
	 * @memberof CodoWechatMPCodeAndLink
	 */
	async createQRCode(path: string, width: number = 430, access_token?: string) {
		access_token = access_token || this.app.codo.wechat.mp.accessToken.getCurrentContextCacheAccessToken();
		const url = `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${access_token}`;

		const res = await this.app.curl(url, {
			method: "POST",
			data: {
				path,
				width,
			},
			rejectUnauthorized: false,
			dataType: "buffer",
		});
		if (res.data.errcode) {
			throw new CodoError(`mp生成永久二维码出错，errcode %s，errmsg %s`, res.data.errcode, res.data.errmsg);
		}
		return res.data as Buffer;
	}
}

/**
 * 获取无限制生成scene值的小程序二维码，可选参数对象
 */
export interface GetUnlimitedQRCodeParams {
	page?: string;
	check_path?: string;
	env_version?: string;
	width?: number;
	auto_color?: boolean;
	line_color?: {
		r: number;
		g: number;
		b: number;
	};
	is_hyaline?: boolean;
}
